<template>
  <div class="site-management">
    <!-- 左侧站点列表 -->
    <div class="site-list">
      <div class="list-header">
        <h3>站点列表</h3>
        <el-button type="primary" size="small" @click="handleAddSite">新增站点</el-button>
      </div>
      <div class="list-search">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入站点名称搜索"
          clearable
          @input="handleSearch"
          @clear="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
      <div class="list-content">
        <el-menu
          :default-active="currentSiteId"
          @select="handleSiteSelect"
        >
          <el-menu-item 
            v-for="site in siteList" 
            :key="site.id" 
            :index="site.id"
            class="site-item"
          >
            <div class="site-item-content">
              <span class="site-name">{{ site.name }}</span>
              <div class="site-actions">
                <el-button 
                  type="primary" 
                  link 
                  @click.stop="handleEditSite(site)"
                >
                  编辑
                </el-button>
                <el-button 
                  type="danger" 
                  link 
                  @click.stop="handleDeleteSite(site)"
                >
                  删除
                </el-button>
              </div>
            </div>
          </el-menu-item>
        </el-menu>
      </div>
    </div>

    <!-- 右侧详情区域 -->
    <div class="site-detail" v-if="currentSite">
      <!-- 站点详情 -->
      <div class="detail-section">
        <div class="section-header">
          <h3>站点详情</h3>
        </div>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="站点名称">{{ currentSite.name }}</el-descriptions-item>
          <el-descriptions-item label="站点编码">{{ currentSite.code }}</el-descriptions-item>
          <el-descriptions-item label="所属工程">{{ currentSite.factory }}</el-descriptions-item>
          <el-descriptions-item label="站点位置">{{ currentSite.location }}</el-descriptions-item>
          <el-descriptions-item label="负责人">{{ currentSite.manager }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ currentSite.contact }}</el-descriptions-item>
          <el-descriptions-item label="站点描述" :span="2">{{ currentSite.description }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 设备列表 -->
      <div class="device-section">
        <div class="section-header">
          <h3>绑定设备</h3>
          <el-button type="primary" size="small" @click="handleBindDevice">绑定新设备</el-button>
        </div>
        <el-table :data="deviceList" style="width: 100%" border>
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column prop="deviceName" label="设备名称" />
          <el-table-column prop="deviceCode" label="设备编码" />
          <el-table-column prop="algorithmType" label="算法类型" />
          <el-table-column prop="status" label="设备状态" width="100" align="center">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" align="center">
            <template #default="scope">
              <el-button 
                type="danger" 
                link
                @click="handleUnbindDevice(scope.row)"
              >
                解除绑定
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 站点表单对话框 -->
    <el-dialog
      v-model="siteDialogVisible"
      :title="dialogType === 'add' ? '新增站点' : '编辑站点'"
      width="500px"
    >
      <el-form
        ref="siteFormRef"
        :model="siteForm"
        :rules="siteFormRules"
        label-width="100px"
      >
        <el-form-item label="站点名称" prop="name">
          <el-input v-model="siteForm.name" placeholder="请输入站点名称" />
        </el-form-item>
        <el-form-item label="站点编码" prop="code">
          <el-input v-model="siteForm.code" placeholder="请输入站点编码" />
        </el-form-item>
        <el-form-item label="所属工程" prop="factory">
          <el-input v-model="siteForm.factory" placeholder="请输入所属工程" />
        </el-form-item>
        <el-form-item label="站点位置" prop="location">
          <el-input v-model="siteForm.location" placeholder="请输入站点位置" />
        </el-form-item>
        <el-form-item label="负责人" prop="manager">
          <el-input v-model="siteForm.manager" placeholder="请输入负责人姓名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contact">
          <el-input v-model="siteForm.contact" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="站点描述" prop="description">
          <el-input
            v-model="siteForm.description"
            type="textarea"
            rows="3"
            placeholder="请输入站点描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="siteDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSiteSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 绑定设备对话框 -->
    <el-dialog
      v-model="bindDeviceDialogVisible"
      title="绑定新设备"
      width="700px"
    >
      <div class="bind-device-dialog">
        <div class="dialog-search">
          <el-input
            v-model="deviceSearchKeyword"
            placeholder="请输入设备名称或编码搜索"
            clearable
            @input="handleDeviceSearch"
            @clear="handleDeviceSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
        <el-table
          :data="availableDevices"
          style="width: 100%"
          border
          @selection-change="handleDeviceSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="deviceName" label="设备名称" />
          <el-table-column prop="deviceCode" label="设备编码" />
          <el-table-column prop="algorithmType" label="算法类型" />
          <el-table-column prop="status" label="设备状态" width="100" align="center">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="bindDeviceDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleBindDeviceSubmit">确定绑定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 站点搜索
const searchKeyword = ref('')
const handleSearch = () => {
  // TODO: 实现站点搜索
  console.log('搜索关键字：', searchKeyword.value)
}

// 站点列表数据
const siteList = ref([
  {
    id: '1',
    name: '监测站点A',
    code: 'SITE001',
    factory: '矿山一号',
    location: '东区入口',
    manager: '张三',
    contact: '13800138001',
    description: '主要负责东区安全监测'
  },
  {
    id: '2',
    name: '监测站点B',
    code: 'SITE002',
    factory: '矿山二号',
    location: '西区中心',
    manager: '李四',
    contact: '13800138002',
    description: '负责西区环境监测'
  },
  {
    id: '3',
    name: '监测站点C',
    code: 'SITE003',
    factory: '矿山一号',
    location: '南区出口',
    manager: '王五',
    contact: '13800138003',
    description: '负责南区交通监控'
  }
])

// 当前选中的站点
const currentSiteId = ref('')
const currentSite = ref(null)

// 站点选择
const handleSiteSelect = (id) => {
  currentSiteId.value = id
  currentSite.value = siteList.value.find(site => site.id === id)
  // TODO: 加载站点绑定的设备列表
}

// 页面加载时默认选中第一个站点
const initDefaultSite = () => {
  if (siteList.value.length > 0) {
    const firstSite = siteList.value[0]
    currentSiteId.value = firstSite.id
    currentSite.value = firstSite
  }
}

// 在组件挂载后调用
onMounted(() => {
  initDefaultSite()
})

// 设备状态
const getStatusType = (status) => {
  const statusMap = {
    online: 'success',
    offline: 'info',
    fault: 'danger',
    disabled: 'warning'
  }
  return statusMap[status]
}

const getStatusText = (status) => {
  const statusMap = {
    online: '在线',
    offline: '离线',
    fault: '故障',
    disabled: '停用'
  }
  return statusMap[status]
}

// 绑定的设备列表
const deviceList = ref([
  {
    deviceName: '摄像头A1',
    deviceCode: 'CAM001',
    algorithmType: '人员检测',
    status: 'online'
  },
  {
    deviceName: '传感器B2',
    deviceCode: 'SEN002',
    algorithmType: '环境监测',
    status: 'online'
  }
])

// 站点表单对话框
const siteDialogVisible = ref(false)
const dialogType = ref('add')
const siteFormRef = ref(null)
const siteForm = reactive({
  name: '',
  code: '',
  factory: '',
  location: '',
  manager: '',
  contact: '',
  description: ''
})

// 站点表单验证规则
const siteFormRules = {
  name: [{ required: true, message: '请输入站点名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入站点编码', trigger: 'blur' }],
  factory: [{ required: true, message: '请输入所属工程', trigger: 'blur' }],
  location: [{ required: true, message: '请输入站点位置', trigger: 'blur' }],
  manager: [{ required: true, message: '请输入负责人姓名', trigger: 'blur' }],
  contact: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

// 新增站点
const handleAddSite = () => {
  dialogType.value = 'add'
  Object.keys(siteForm).forEach(key => siteForm[key] = '')
  siteDialogVisible.value = true
}

// 编辑站点
const handleEditSite = (site) => {
  dialogType.value = 'edit'
  Object.keys(siteForm).forEach(key => siteForm[key] = site[key])
  siteDialogVisible.value = true
}

// 删除站点
const handleDeleteSite = (site) => {
  ElMessageBox.confirm(
    `确定要删除站点"${site.name}"吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // TODO: 调用删除接口
    ElMessage.success('删除成功')
  }).catch(() => {})
}

// 提交站点表单
const handleSiteSubmit = async () => {
  if (!siteFormRef.value) return
  await siteFormRef.value.validate((valid) => {
    if (valid) {
      // TODO: 调用新增或编辑接口
      console.log('表单数据：', siteForm)
      ElMessage.success(dialogType.value === 'add' ? '新增成功' : '编辑成功')
      siteDialogVisible.value = false
    }
  })
}

// 绑定设备相关
const bindDeviceDialogVisible = ref(false)
const deviceSearchKeyword = ref('')
const selectedDevices = ref([])

// 可选设备列表
const availableDevices = ref([
  {
    deviceName: '摄像头C3',
    deviceCode: 'CAM003',
    algorithmType: '车辆识别',
    status: 'online'
  },
  {
    deviceName: '气体检测器D4',
    deviceCode: 'GAS004',
    algorithmType: '有害气体检测',
    status: 'online'
  }
])

// 设备搜索
const handleDeviceSearch = () => {
  // TODO: 实现设备搜索
  console.log('设备搜索关键字：', deviceSearchKeyword.value)
}

// 打开绑定设备对话框
const handleBindDevice = () => {
  selectedDevices.value = []
  bindDeviceDialogVisible.value = true
}

// 设备选择变化
const handleDeviceSelectionChange = (selection) => {
  selectedDevices.value = selection
}

// 提交设备绑定
const handleBindDeviceSubmit = () => {
  if (selectedDevices.value.length === 0) {
    ElMessage.warning('请选择要绑定的设备')
    return
  }
  // TODO: 调用绑定设备接口
  console.log('绑定设备：', selectedDevices.value)
  ElMessage.success('绑定成功')
  bindDeviceDialogVisible.value = false
}

// 解除设备绑定
const handleUnbindDevice = (device) => {
  ElMessageBox.confirm(
    `确定要解除设备"${device.deviceName}"的绑定吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // TODO: 调用解除绑定接口
    ElMessage.success('解除绑定成功')
  }).catch(() => {})
}
</script>

<style scoped>
.site-management {
  height: 100%;
  display: flex;
  gap: 16px;
}

/* 左侧站点列表样式 */
.site-list {
  width: 300px;
  background-color: #fff;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
}

.list-header {
  padding: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #e6e6e6;
}

.list-header h3 {
  margin: 0;
  font-size: 16px;
}

.list-search {
  padding: 16px;
  border-bottom: 1px solid #e6e6e6;
}

.list-content {
  flex: 1;
  overflow-y: auto;
}

.site-item {
  padding: 0 16px;
}

.site-item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.site-name {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.site-actions {
  display: none;
}

.site-item:hover .site-actions {
  display: flex;
  gap: 8px;
}

/* 右侧详情区域样式 */
.site-detail {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 16px;
  min-width: 0;
}

.detail-section, .device-section {
  background-color: #fff;
  border-radius: 4px;
  padding: 16px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-header h3 {
  margin: 0;
  font-size: 16px;
}

/* 对话框样式 */
.bind-device-dialog {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.dialog-search {
  margin-bottom: 16px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-menu) {
  border-right: none;
}

:deep(.el-menu-item) {
  height: 50px;
  line-height: 50px;
}

:deep(.el-menu-item.is-active) {
  background-color: var(--el-menu-hover-bg-color);
}
</style>